// 微信小程序入口文件
App({
  globalData: {
    // 用户信息
    userInfo: {
      isLoggedIn: false,
      nickname: '',
      avatar: '/images/NY_RectangularFavicon.png',
      description: '',
      username: '',
      permissions: []
    },
    token: null,

    // 应用配置
    apiBaseUrl: 'https://college.guducat.cn/api',
    appVersion: '1.0.0',

    // 收藏和历史记录
    favorites: [],
    history: [],

    // 新闻数据
    newsData: {
      homeNews: [],
      searchResults: [],
      categories: [],
      sections: [],
      currentPage: 1,
      totalPages: 0,
      pageSize: 10,
      hasMore: true,
      searchKeyword: '',
      selectedCategory: '',
      selectedSection: ''
    },

    // 应用状态
    appState: {
      networkStatus: 'online',
      loading: false,
      globalLoading: false,
      theme: 'light',
      debugMode: false
    }
  },

  onLaunch: function() {
    console.log('小程序启动')

    // 初始化应用
    this.initApp()
  },

  onShow: function() {
    console.log('小程序显示')
  },

  onHide: function() {
    console.log('小程序隐藏')
  },

  onError: function(error) {
    console.error('小程序错误:', error)
  },

  // 初始化应用
  initApp: function() {
    // 检查登录状态
    this.checkLoginStatus()

    // 加载本地数据
    this.loadLocalData()

    // 检查网络状态
    this.checkNetworkStatus()
  },

  // 检查登录状态
  checkLoginStatus: function() {
    try {
      const token = wx.getStorageSync('token')
      const userInfo = wx.getStorageSync('userInfo')

      console.log('检查登录状态 - token:', token)
      console.log('检查登录状态 - userInfo:', userInfo)

      if (token && userInfo) {
        this.globalData.token = token
        this.globalData.userInfo = {
          ...this.globalData.userInfo,
          ...userInfo,
          isLoggedIn: true
        }
        console.log('登录状态已恢复:', this.globalData.userInfo)
      } else {
        // 确保未登录状态
        this.globalData.userInfo.isLoggedIn = false
        console.log('未找到登录信息，设置为未登录状态')
      }
    } catch (error) {
      console.error('检查登录状态失败:', error)
      this.globalData.userInfo.isLoggedIn = false
    }
  },

  // 加载本地数据
  loadLocalData: function() {
    try {
      // 加载收藏数据
      const favorites = wx.getStorageSync('favorites')
      if (favorites) {
        this.globalData.favorites = favorites
      }

      // 加载历史记录
      const history = wx.getStorageSync('history')
      if (history) {
        this.globalData.history = history
      }
    } catch (error) {
      console.error('加载本地数据失败:', error)
    }
  },

  // 检查网络状态
  checkNetworkStatus: function() {
    const that = this
    wx.getNetworkType({
      success: function(res) {
        that.globalData.appState.networkStatus = res.networkType === 'none' ? 'offline' : 'online'
      }
    })

    // 监听网络状态变化
    wx.onNetworkStatusChange(function(res) {
      that.globalData.appState.networkStatus = res.isConnected ? 'online' : 'offline'
    })
  },

  // 设置用户信息
  setUserInfo: function(userInfo, token) {
    console.log('设置用户信息 - 输入参数:', { userInfo, token })

    this.globalData.userInfo = {
      ...this.globalData.userInfo,
      ...userInfo,
      isLoggedIn: true
    }

    if (token) {
      this.globalData.token = token
    }

    console.log('设置用户信息 - 最终状态:', this.globalData.userInfo)
    console.log('设置用户信息 - token:', this.globalData.token)

    // 保存到本地存储
    try {
      wx.setStorageSync('userInfo', this.globalData.userInfo)
      if (token) {
        wx.setStorageSync('token', token)
      }
      console.log('用户信息已保存到本地存储')
    } catch (error) {
      console.error('保存用户信息失败:', error)
    }
  },

  // 清除用户信息
  clearUserInfo: function() {
    console.log('清除用户信息')

    this.globalData.userInfo = {
      isLoggedIn: false,
      nickname: '',
      avatar: '/images/NY_RectangularFavicon.png',
      description: '',
      username: '',
      permissions: []
    }
    this.globalData.token = null

    console.log('用户信息已清除:', this.globalData.userInfo)

    // 清除本地存储
    try {
      wx.removeStorageSync('userInfo')
      wx.removeStorageSync('token')
      console.log('本地存储已清除')
    } catch (error) {
      console.error('清除用户信息失败:', error)
    }
  },

  // 检查是否有管理员权限
  hasAdminPermission: function() {
    const permissions = this.globalData.userInfo.permissions || []
    return permissions.some(function(perm) {
      return perm !== '学生' && perm !== '教师'
    })
  },

  // 检查是否已认证
  isAuthenticated: function() {
    return this.globalData.userInfo.isLoggedIn && !!this.globalData.token
  },

  // 更新用户信息
  updateUserInfo: function(updates) {
    this.globalData.userInfo = {
      ...this.globalData.userInfo,
      ...updates
    }

    try {
      wx.setStorageSync('userInfo', this.globalData.userInfo)
    } catch (error) {
      console.error('更新用户信息失败:', error)
    }
  },

  // 添加收藏
  addFavorite: function(article) {
    const favorites = this.globalData.favorites
    const exists = favorites.find(function(item) {
      return item.news_id === article.news_id
    })

    if (!exists) {
      favorites.unshift(article)
      this.globalData.favorites = favorites

      // 保存到本地存储
      try {
        wx.setStorageSync('favorites', favorites)
      } catch (error) {
        console.error('保存收藏失败:', error)
      }
    }
  },

  // 移除收藏
  removeFavorite: function(newsId) {
    const favorites = this.globalData.favorites.filter(function(item) {
      return item.news_id !== newsId
    })
    this.globalData.favorites = favorites

    // 保存到本地存储
    try {
      wx.setStorageSync('favorites', favorites)
    } catch (error) {
      console.error('保存收藏失败:', error)
    }
  },

  // 检查是否已收藏
  isFavorited: function(newsId) {
    return this.globalData.favorites.some(function(item) {
      return item.news_id === newsId
    })
  },

  // 添加历史记录
  addHistory: function(article) {
    const history = this.globalData.history

    // 移除已存在的记录
    const filteredHistory = history.filter(function(item) {
      return item.news_id !== article.news_id
    })

    // 添加到开头
    filteredHistory.unshift({
      ...article,
      viewTime: new Date().toISOString()
    })

    // 限制历史记录数量
    if (filteredHistory.length > 100) {
      filteredHistory.splice(100)
    }

    this.globalData.history = filteredHistory

    // 保存到本地存储
    try {
      wx.setStorageSync('history', filteredHistory)
    } catch (error) {
      console.error('保存历史记录失败:', error)
    }
  },

  // 清除历史记录
  clearHistory: function() {
    this.globalData.history = []

    try {
      wx.removeStorageSync('history')
    } catch (error) {
      console.error('清除历史记录失败:', error)
    }
  },

  // 设置新闻数据
  setNewsData: function(key, data) {
    if (this.globalData.newsData.hasOwnProperty(key)) {
      this.globalData.newsData[key] = data
    }
  },

  // 添加新闻到列表
  addNewsToList: function(newsList, append = false) {
    if (append) {
      this.globalData.newsData.homeNews = this.globalData.newsData.homeNews.concat(newsList)
    } else {
      this.globalData.newsData.homeNews = newsList
    }
  },

  // 设置搜索结果
  setSearchResults: function(results, append = false) {
    if (append) {
      this.globalData.newsData.searchResults = this.globalData.newsData.searchResults.concat(results)
    } else {
      this.globalData.newsData.searchResults = results
    }
  },

  // 设置分类数据
  setCategories: function(categories) {
    this.globalData.newsData.categories = categories
  },

  // 设置学院数据
  setSections: function(sections) {
    this.globalData.newsData.sections = sections
  },

  // 设置搜索参数
  setSearchParams: function(params) {
    if (params.keyword !== undefined) {
      this.globalData.newsData.searchKeyword = params.keyword
    }
    if (params.category !== undefined) {
      this.globalData.newsData.selectedCategory = params.category
    }
    if (params.section !== undefined) {
      this.globalData.newsData.selectedSection = params.section
    }
  },

  // 设置分页信息
  setPagination: function(currentPage, totalPages, hasMore) {
    this.globalData.newsData.currentPage = currentPage
    this.globalData.newsData.totalPages = totalPages || 0
    this.globalData.newsData.hasMore = hasMore !== undefined ? hasMore : true
  },

  // 设置应用状态
  setAppState: function(key, value) {
    if (this.globalData.appState.hasOwnProperty(key)) {
      this.globalData.appState[key] = value
    }
  },

  // 设置加载状态
  setLoading: function(loading) {
    this.globalData.appState.loading = loading
  },

  // 设置全局加载状态
  setGlobalLoading: function(loading) {
    this.globalData.appState.globalLoading = loading
  },

  // 设置主题
  setTheme: function(theme) {
    this.globalData.appState.theme = theme
    try {
      wx.setStorageSync('theme', theme)
    } catch (error) {
      console.error('保存主题设置失败:', error)
    }
  },

  // 切换主题
  toggleTheme: function() {
    const newTheme = this.globalData.appState.theme === 'light' ? 'dark' : 'light'
    this.setTheme(newTheme)
  },

  // 设置调试模式
  setDebugMode: function(debug) {
    this.globalData.appState.debugMode = debug
  }
})
